package com.xingkeduo.configuration;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Configuration;

@Configuration
public class ChannelFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
        }
        ServletResponse responseWrapper = null;
//        if(servletResponse instanceof HttpServletResponse) {
//        	responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
//        }
        if(requestWrapper == null && responseWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else if(requestWrapper != null && responseWrapper == null){
            filterChain.doFilter(requestWrapper, servletResponse);
        }else if(requestWrapper == null && responseWrapper != null){
            filterChain.doFilter(servletRequest, responseWrapper);
            String responseString = ((ResponseWrapper) responseWrapper).getResponseData(servletResponse.getCharacterEncoding());
           // System.out.println("RESPONSE-DATA:"+responseString);
            servletResponse.getOutputStream().write(responseString.getBytes(servletResponse.getCharacterEncoding()));
        }else if(requestWrapper != null && responseWrapper != null){
            filterChain.doFilter(requestWrapper, responseWrapper);
            String responseString = ((ResponseWrapper) responseWrapper).getResponseData(servletResponse.getCharacterEncoding());
         //   System.out.println("RESPONSE-DATA:"+responseString);
            servletResponse.getOutputStream().write(responseString.getBytes(servletResponse.getCharacterEncoding()));
        }
        
    }
}
